/**
 * layui+thinkphp简化使用的框架
 * @huhaiqin
 */
var think_open_dialog; //替代一下之前的open_iframe_dialog
var think_table = []; //注册一下被渲染的table
layui.define(['layer', 'jquery', 'laypage', 'upload', 'laytpl', 'form', 'table', 'weui', 'element'], function(exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        laypage = layui.laypage,
        laytpl = layui.laytpl,
        form = layui.form,
        table = layui.table;

    listen_ajax_click(); //进来默认监听
    function listen_ajax_click() {
        //表单提交
        form.on('submit(*)', function(data) {
            var action = $(data.form).attr('action'),
                button = $(data.elem);
            var $form = $(data.form);
            if ($form.hasClass('submit-holder')) {
                return; //禁止提交，防止重复提交
            }
            var ii;
            $.ajax({
                url: action,
                data: data.field,
                type: "POST",
                dataType: "json",
                beforeSend: function() {
                    $form.addClass('submit-holder'); //防止重复提交
                    ii = layer.msg('Loading...', { icon: 16, time: 10000 });
                },
                complete: function() {
                    layer.close(ii);
                    $form.removeClass('submit-holder'); //解除禁止提交
                },
                success: function(data) {
                    //data = JSON.parse(data);  //str 转 json
                    if (data.status == 1) {
                        layer.msg(data.info, { icon: 1, time: 1000 }, function() {
                            if (data.url) {
                                location.href = data.url;
                            }

                            //关闭父窗口
                            if ($form.hasClass('close-dialog')) {
                                //如果有callback样式，表示成功后要执行回调
                                if ($form.hasClass('callback')) {
                                    parent.mini_callback(data.data); //传一个参数进去
                                }
                                if ($form.hasClass('parent-refresh')) {
                                    parent.location.reload();
                                }
                                parent.think_close();
                            } else {
                                //执行本地回调方法
                                if ($form.hasClass('self-callback')) {
                                    self_callback(); //本地回调
                                }

                                if ($form.hasClass('callback')) {
                                    parent.mini_callback();
                                }

                                if ($form.hasClass('parent-refresh')) {
                                    parent.location.reload();
                                }

                                if ($form.hasClass('shuaxin')) {
                                    location.reload(); //刷新
                                }
                            }
                        });

                    } else {
                        layer.msg(data.info, { icon: 2, time: 1000 });
                    }
                    //需要跳转的话
                    if (data.url) {
                        setTimeout(function() {
                            location.href = data.url;
                        }, 1000);
                    }

                }
            });
            return false;
        });
        //删除操作
        $('.mini_del').unbind('click').click(function() {

            var $this = $(this);
            var msg = typeof($(this).data('msg')) == 'undefined' ? '确定删除吗？' : $(this).data('msg');
            var asker = layer.confirm(msg, function() {
                var ii;
                $.ajax({
                    url: $this.attr('data-url'),
                    type: "get",
                    dataType: "json",
                    beforeSend: function() {
                        ii = layer.msg('Loading...', { icon: 16, time: 10000 });
                    },
                    complete: function() {
                        layer.close(ii);
                    },
                    success: function(data) {
                        if (data.status) {
                            layer.msg('删除成功', { icon: 1, time: 1000 }, function() {
                                if ($this.hasClass('reload') || $this.hasClass('shuaxin')) {
                                    location.reload(); //自动关闭后可做一些刷新页面等操作
                                } else {
                                    //重新渲染表格
                                    for (var i = 0; i < think_table.length; i++) {
                                        table.reload(think_table[i]);
                                    }
                                }

                            });
                        } else {
                            layer.msg(data.info, { icon: 2, time: 1000 });
                        }
                    }
                });
            });
        });

        $('.ajax-post').unbind('click').click(function() {
            var $this = $(this);
            var target_form = $(this).attr('target-form');
            var form = $('.' + target_form);
            var query = form.serialize();
            var msg = $this.attr('data-msg');
            if (!query) {
                layer.alert('没有可操作的数据', { icon: 7 });
                return false;
            }

            if (!msg) {
                msg = '确定删除吗？';
            }


            if ($this.hasClass('confirm')) {
                var asker = layer.confirm(msg, function() {

                    var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });

                    $.post($this.attr('data-url'), query, function(data) {
                        layer.close(ii);
                        if (data.status) {
                            layer.msg(data.info, { icon: 1, time: 1000 }, function() {
                                //关闭父窗口
                                if ($this.hasClass('close-dialog')) {
                                    parent.think_close();
                                    return;
                                }
                                if ($this.hasClass('shuaxin')) {
                                    location = location;
                                    return;
                                }
                                if ($this.hasClass('parent-refresh')) {
                                    parent.refresh();
                                    return;
                                }
                                //默认重新刷新表格
                                for (var i = 0; i < think_table.length; i++) {
                                    table.reload(think_table[i]);
                                }
                            });
                        } else {
                            layer.msg(data.info, { icon: 2, time: 1000 });
                        }

                        //需要跳转的话
                        if (data.info != 'You do not have this authority') {
                            if (data.url) {
                                setTimeout(function() {
                                    location.href = data.url;
                                }, 1000);
                            }
                        }

                    }, 'json');
                });

            } else {
                var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });

                $.post($this.attr('data-url'), query, function(data) {
                    layer.close(ii);
                    if (data.status) {
                        layer.msg(data.info, { icon: 1, time: 1000 }, function() {
                            //关闭父窗口
                            if ($this.hasClass('close-dialog')) {
                                parent.think_close();
                                return;
                            }
                            if ($this.hasClass('shuaxin')) {
                                location = location;
                                return;
                            }
                            if ($this.hasClass('parent-refresh')) {
                                parent.refresh();
                                return;
                            }
                            //默认重新刷新表格
                            for (var i = 0; i < think_table.length; i++) {
                                table.reload(think_table[i]);
                            }
                        });
                    } else {
                        layer.msg(data.info, { icon: 2, time: 1000 });
                    }

                    //需要跳转的话
                    if (data.info != 'You do not have this authority') {
                        if (data.url) {
                            setTimeout(function() {
                                location.href = data.url;
                            }, 1000);
                        }
                    }
                }, 'json');

            }
            return false;

        });

        $('.ajax-get').unbind('click').click(function() {
            var $this = $(this);
            var msg = $(this).attr('data-msg');
            if (!msg) {
                msg = '确定删除吗？';
            }
            if ($this.hasClass('confirm')) {
                var asker = layer.confirm(msg, function() {
                    var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });
                    $.get($this.attr('data-url'), function(data) {
                        layer.close(ii);
                        if (data.status) {
                            layer.msg(data.info, { icon: 1, time: 1000 }, function() {
                                //关闭父窗口
                                if ($this.hasClass('close-dialog')) {
                                    parent.think_close();
                                    return;
                                }
                                if ($this.hasClass('shuaxin')) {
                                    location = location;
                                    return;
                                }
                                if ($this.hasClass('parent-refresh')) {
                                    parent.refresh();
                                    return;
                                }
                                //默认重新刷新表格
                                for (var i = 0; i < think_table.length; i++) {
                                    table.reload(think_table[i]);
                                }
                            });
                        } else {
                            layer.msg(data.info, { icon: 2, time: 1000 });
                        }

                        //需要跳转的话
                        if (data.info != 'You do not have this authority') {
                            if (data.url) {
                                setTimeout(function() {
                                    location.href = data.url;
                                }, 1000);
                            }
                        }

                    }, 'json');
                });
            } else {
                var ii = layer.msg('数据处理中...', { icon: 16, time: 10000 });
                $.get($this.attr('data-url'), function(data) {
                    layer.close(ii);
                    if (data.status) {
                        layer.msg(data.info, { icon: 1, time: 1000 }, function() {
                            //关闭父窗口
                            if ($this.hasClass('close-dialog')) {
                                parent.think_close();
                                return;
                            }
                            if ($this.hasClass('shuaxin')) {
                                location = location;
                                return;
                            }
                            if ($this.hasClass('parent-refresh')) {
                                parent.refresh();
                                return;
                            }
                            //默认重新刷新表格
                            for (var i = 0; i < think_table.length; i++) {
                                table.reload(think_table[i]);
                            }
                        });
                    } else {
                        layer.msg(data.info, { icon: 2, time: 1000 });
                    }
                    //需要跳转的话
                    if (data.info != 'You do not have this authority') {
                        if (data.url) {
                            setTimeout(function() {
                                location.href = data.url;
                            }, 1000);
                        }
                    }
                }, 'json');
            }
        });
    }
    var loading;
    var think = {
        guid: function() {
            var d = new Date().getTime();
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        },
        show_loading: function(msg = 'loading') {
            loading = weui.loading(msg, {
                className: 'custom-classname'
            });
        },
        hide_loading: function() {
            loading.hide();
        },
        ajaxlisten: function() {
            listen_ajax_click();
        },
        render: function(config = {}, searchtype = '', keyword = '', linkTpl = '', linkParam = '') {
            //改写table.render(config)
            //config与table.render的格式一致，searchtype+keyword用于搜索的时候关键词描红
            var tmp_searchtype = searchtype.split("."); //需要处理一下带别名的字段
            if (tmp_searchtype.length == 2) {
                searchtype = tmp_searchtype[1];
            } else {
                searchtype = tmp_searchtype[0];
            }
            var redtpl = function(d) {
                var tmp = replace_str_all(d[searchtype], keyword, '<span style="color:red">' + keyword + '</span>');
                if (linkTpl != '') {
                    linkTpl = replace_str_all(linkTpl, '#param#', d[linkParam]);
                    tmp = '<a href="' + linkTpl + '">' + tmp + '</a>';
                }
                return tmp;
            }

            if (searchtype != '' && keyword != '') {
                for (var i = 0; i < config.cols[0].length; i++) {
                    if (searchtype == config.cols[0][i].field) {
                        config.cols[0][i].templet = redtpl;
                        break; //跳出循环
                    }
                }
            }
            if (typeof(config.page) == 'undefined') {
                config.page = true;
            }
            if (typeof(config.id) == 'undefined') {
                config.id = guid();
            }

            $(config.elem).attr('data-id', config.id);
            think_table.push(config.id); //注册一下渲染
            if (typeof(config.done) == 'undefined') {
                config.done = function(res) {
                    listen_ajax_click();
                    $('.think-btn').unbind('click').click(function() {
                        var $this = $(this);
                        //执行删除操作
                        var checkStatus = table.checkStatus(config.id),
                            checkData = checkStatus.data; //得到选中的数据
                        if (checkData.length === 0) {
                            return layer.msg('请选择数据');
                        }
                        var ids = [];
                        for (var v in checkData) {
                            ids.push(checkData[v].id);
                        }
                        if ($this.data('type') == 'del') {
                            if ($this.data('url')) {
                                layer.confirm('确定删除吗？', function(index) {
                                    $.post($this.data('url'), {
                                        ids: ids
                                    }, function(ret) {
                                        if (ret.status === 1) {
                                            layer.close(index);
                                            layer.msg(ret.info, { icon: 1, time: 1000 }, function() {
                                                table.reload(config.id); //重载数据
                                            });
                                        } else {
                                            layer.msg(ret.info);
                                        }
                                    }, 'json');
                                });
                            } else {
                                //没有配置ajax的地址
                            }
                        } else {
                            if ($this.data('url')) {
                                var msg = $this.data('msg');
                                if (msg != '') {
                                    layer.confirm(msg, function(index) {
                                        $.post($this.data('url'), {
                                            ids: ids
                                        }, function(ret) {
                                            if (ret.status === 1) {
                                                layer.close(index);
                                                layer.msg(ret.info, { icon: 1, time: 1000 }, function() {
                                                    table.reload(config.id); //重载数据
                                                });
                                            } else {
                                                layer.msg(ret.info);
                                            }
                                        }, 'json');
                                    });
                                } else {
                                    $.post($this.data('url'), {
                                        ids: ids
                                    }, function(ret) {
                                        if (ret.status === 1) {
                                            layer.close(index);
                                            layer.msg(ret.info, { icon: 1, time: 1000 }, function() {
                                                table.reload(config.id); //重载数据
                                            });
                                        } else {
                                            layer.msg(ret.info);
                                        }
                                    }, 'json');
                                }
                            } else {
                                //2021.12.20 更新，think-btn支持回调函数
                                if ($this.data('action')) {
                                    var action = eval($this.data('action'));
                                    new action(ids); //执行这个新方法
                                }
                            }
                        }
                    });
                }
            }

            table.render(config);
        },
        //js加载css
        include_css: function(filename) {
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = filename;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            head.appendChild(link)
        },
        //js加载js
        include_js: function(filename) {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = filename;
            script.type = 'text/javascript';
            head.appendChild(script)
        },
        load_js: function(url = '', callback = function() {}) {　　
            var script = document.createElement('script');　　　　
            script.type = 'text/javascript';　　　　
            script.async = 'async';　　　　
            script.src = url;　　　　
            document.body.appendChild(script);　　　　
            if (script.readyState) {
                script.onreadystatechange = function() {
                    if (script.readyState == 'complete' || script.readyState == 'loaded') {
                        script.onreadystatechange = null;
                        callback();
                    }
                }
            } else {
                //非IE
                script.onload = function() {
                    callback();
                }
            }
        }
    };

    // 2023.03.19 上传图片支持
    /*
    <div class="layui-form-item">
        <label class="layui-form-label">Logo：</label>
        <div class="layui-input-block">
            <div class="xy-upload">
                <input type="text" name="logo" style="width:400px;display:inline-block" value="{$info.logo}" placeholder="请输入Logo地址" class="layui-input xy-upload-img-input">
                <a href="javascript:;" class="layui-btn xy-upload-img">上传Logo</a>
                <div class="xy-upload-img-box" style="background:#f8f8f8;text-align:center;">
                    <if condition="$info['logo']">
                        <img src="{$info.logo}">
                        <else/>
                        <span style="font-size:30px;line-height:80px;color:#eee;">Logo</span>
                    </if>
                </div>
            </div>
        </div>
    </div>
    */
    layui.upload.render({
        url: '/system/upload/img',
        elem: '.xy-upload-img',
        ext: 'jpg|png|gif|bmp|jpeg|ico',
        method: 'post',
        accept: 'images',
        auto: false,
        choose: function(obj) { //选择文件后的回调
            var files = obj.pushFile();
            var filesArry = [];
            for (var key in files) { //将上传的文件转为数组形式
                filesArry.push(files[key])
            }
            var index = filesArry.length - 1;
            var file = filesArry[index]; //获取最后选择的图片,即处理多选情况

            if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
                    .replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
                return obj.upload(index, file)
            }
            canvasDataURL(file, function(blob) {
                var aafile = new File([blob], file.name, {
                    type: file.type
                })
                var isLt1M;
                if (file.size < aafile.size) {
                    isLt1M = file.size
                } else {
                    isLt1M = aafile.size
                }

                if (isLt1M / 1024 / 1024 > 2) {
                    return layer.alert('上传图片过大！')
                } else {
                    if (file.size < aafile.size) {
                        return obj.upload(index, file)
                    }
                    obj.upload(index, aafile)
                }
            })
        },
        before: function() {
            ii = layer.msg('uploading...', {
                icon: 16,
                time: 10000
            });
        },
        done: function(ret) {
            var $dom = this.item; //获取出发上传的done
            console.log($dom.parent('.xy-upload').find('.xy-upload-img-box').html());
            console.log($dom);
            if (ret.status) {
                xy_change_img($dom.parent('.xy-upload').find('.xy-upload-img-box'), ret.data.url);
                layer.close(ii);
            } else {
                layer.alert(ret.info);
            }
        }
    });

    //上传多图
    layui.upload.render({
        url: '/system/upload/img',
        elem: '.xy-upload-imgs',
        ext: 'jpg|png|gif|bmp|jpeg|ico',
        method: 'post',
        accept: 'images',
        auto: false,
        choose: function(obj) { //选择文件后的回调
            var files = obj.pushFile();
            var filesArry = [];
            for (var key in files) { //将上传的文件转为数组形式
                filesArry.push(files[key])
            }
            var index = filesArry.length - 1;
            var file = filesArry[index]; //获取最后选择的图片,即处理多选情况

            if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
                    .replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
                return obj.upload(index, file)
            }
            canvasDataURL(file, function(blob) {
                var aafile = new File([blob], file.name, {
                    type: file.type
                })
                var isLt1M;
                if (file.size < aafile.size) {
                    isLt1M = file.size
                } else {
                    isLt1M = aafile.size
                }

                if (isLt1M / 1024 / 1024 > 2) {
                    return layer.alert('上传图片过大！')
                } else {
                    if (file.size < aafile.size) {
                        return obj.upload(index, file)
                    }
                    obj.upload(index, aafile)
                }
            })
        },
        before: function() {
            ii = layer.msg('uploading...', {
                icon: 16,
                time: 10000
            });
        },
        done: function(ret) {
            // var $dom = this.item; //获取出发上传的done
            // console.log($dom.parent('.xy-upload').find('.xy-upload-img-box').html());
            // console.log($dom);
            if (ret.status) {
                var id = guid();
                var html = '<div class="img-box" id="' + id + '">' +
                    '<div class="img-box-img">' +
                    '<img src="' + ret.data.url + '?imageView2/1/w/300/h/300/q/75">' +
                    // '<input type="hidden" name="imglist[]" value="{id:' + ret.data.id + ',url:\'' + ret.data.url + '\'}">' +
                    '<textarea style="display: none;" name="imglist[]">{"id":' + ret.data.id + ',"url":"' + ret.data.url + '"}</textarea>' +
                    '</div>' +
                    '<div class="img-box-action layui-clear">' +
                    '<a href="javascript:think_remove_dom(\'#' + id + '\');" class="layui-btn layui-btn-sm layui-btn-danger fr">删除</a>' +
                    '</div>' +
                    '</div>';
                $('#img-list').append(html);
                layer.close(ii);
            } else {
                layer.alert(ret.info);
            }
        }
    });

    function canvasDataURL(file, callback) { //压缩转化为base64
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function(e) {
            const img = new Image()
            const quality = 0.75 // 图像质量
            const canvas = document.createElement('canvas')
            const drawer = canvas.getContext('2d')
            img.src = this.result
            var scale = 1
            img.onload = function() {
                //如图图片太宽或太高，则需要压缩尺寸
                if (img.width > 2000 || img.height > 2000) {
                    scale = 0.5
                }
                canvas.width = img.width * scale
                canvas.height = img.height * scale
                drawer.drawImage(img, 0, 0, canvas.width, canvas.height)
                convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback);
            }
        }
    }

    function convertBase64UrlToBlob(urlData, callback) { //将base64转化为文件格式
        const arr = urlData.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        callback(new Blob([u8arr], {
            type: mime
        }));
    }


    //监听封面图改变
    $('.xy-upload-img-input').change(function() {
        xy_change_img($(this).parent('.xy-upload').find('.xy-upload-img-box'), $(this).val());
    });

    function xy_change_img($dom, url) {
        // $dom 对应 .xy-upload-img-box
        $dom.parent('.xy-upload').find('.xy-upload-img-input').val(url);
        $dom.html('<img src="' + url + '">');
        $dom.unbind('click').click(function() {
            var $this = $(this);
            //调用示例
            layer.photos({
                photos: $dom,
                anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
            });
        });
    }

    think.include_css('/Public/weui.2x/weui.min.css');
    exports('think', think);
});

//删除dom
function think_remove_dom(dom) {
    layui.use(['jquery', 'layer'], function() {
        var $ = layui.jquery,
            layer = layui.layer;
        var t = layer.confirm('确定删除吗？', function(index) {
            $(dom).remove();
            layer.close(t);
        });
    });
}

/**
 * 字符串替代
 */
function replace_str_all(str, oldStr, newStr) {
    var reg = new RegExp(oldStr, "g");
    str = str.replace(reg, newStr);
    return str;
}

//string转json
function str_to_json(str) {
    return eval('(' + str + ')');
}

//json转string
function json_to_str(obj) {
    return JSON.stringify(obj);
}

//生成唯一ID
function guid() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

function think_open(url_p, title_p, options_p, is_reload) {
    if (!options_p) {
        options_p = ['1024px', '500px'];
    }

    think_open_dialog = layer.open({
        type: 2,
        title: title_p,
        maxmin: true,
        shadeClose: true,
        area: options_p,
        content: url_p, //iframe的url，no代表不显示滚动条
        // cancel: function() {
        //     location.reload();
        // },
        end: function() { //此处用于演示
            if (is_reload) {
                location.reload(); //当前页面是否需要刷新
            }
        }
    });

}

function think_close() {
    layui.use(['jquery', 'table'], function() {
        var $ = layui.jquery,
            table = layui.table;
        for (var i = 0; i < think_table.length; i++) {
            table.reload(think_table[i]);
        }
    })

    layer.close(think_open_dialog);
}

function think_reload() {
    layui.use(['jquery', 'table'], function() {
        var $ = layui.jquery,
            table = layui.table;
        for (var i = 0; i < think_table.length; i++) {
            table.reload(think_table[i]);
        }
    })

}

//时间戳转格式时间'2019-10-10 11:11:11'
var think_time = function(timestamp, formats) {
    if (typeof(timestamp) == 'string') {
        timestamp = parseInt(timestamp);
    }
    timestamp = timestamp * 1000; //我们一般用10位，需要补000变成毫秒
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d';

    var zero = function(value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    var myDate = timestamp ? new Date(timestamp) : new Date();

    var year = myDate.getFullYear();
    var month = zero(myDate.getMonth() + 1);
    var day = zero(myDate.getDate());

    var hour = zero(myDate.getHours());
    var minite = zero(myDate.getMinutes());
    var second = zero(myDate.getSeconds());

    return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches];
    });
};

//js去除html标签，eg: sTest.stripHTML()
String.prototype.stripHTML = function() {
    var reTag = /<(?:.|\s)*?>/g;
    return this.replace(reTag, "");
}

// 获取当前的时间戳
function time() {
    let outcome = Math.round(new Date().getTime() / 1000).toString();
    return outcome
}